﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using SoufunData.DB;

namespace SoufunData
{
    public partial class ExToDbBBusinessManage : DevExpress.XtraEditors.XtraForm
    {
        public ExToDbBBusinessManage()
        {
            InitializeComponent();
        }

        private void btn_excelPath_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

            openFileDialog1.Filter = "Excel文件|*.xls;*.xlsx";
            openFileDialog1.FileName = "";
            openFileDialog1.ShowDialog();
            string fileName = openFileDialog1.FileName;
            btn_excelPath.Text = fileName;

            gridControl2.DataSource = null;
            gridView2.Columns.Clear();
            gridView2.GroupPanelText = "请选择Excel文件";
            if (fileName == "")
            {
                return;
            }
            DataSet ds = Common.LoadDataFromExcel(fileName);
            if (ds == null || ds.Tables.Count == 0)
            {
                string strError = "读取Excel时发生错误，请核对：\r\n ";
                strError += "1，导入时请在Excel中关闭想要导入的文件！\r\n";
                strError += "2，导入的Excel表中的工作表名称必须为Sheet1,否者程序无法读取！\r\n";
                strError += "3，请确保您的计算机安装了Microsoft Office！\r\n";
                strError += "4，请确保导入的Excel文件正常！";
                XtraMessageBox.Show(strError);
                btn_excelPath.Text = "";
                return;
            }  
            if (!CheckExcelColumnsName(ds.Tables[0]))
            {
                btn_excelPath.Text = "";
                return;
            }
            List<string> deleteColumns = new List<string>();
            foreach (DataColumn column in ds.Tables[0].Columns)
            {
                if (column.ColumnName.Contains("F"))
                {
                    deleteColumns.Add(column.ColumnName);
                }
            }
            foreach (string column in deleteColumns)
            {
                ds.Tables[0].Columns.Remove(column);
            }
            gridControl2.DataSource = ds.Tables[0]; 
            gridView2.GroupPanelText = "共有" + ds.Tables[0].Rows.Count + "条数据";
        }


        private void AddData()
        {
           
            DataTable dtOld = (DataTable)gridControl2.DataSource;

            DataTable dt = dtOld.Copy();
            dt.Rows.Clear();
            foreach (DataRow dataRow in dtOld.Rows)
            { 
                dt.Rows.Add(dataRow.ItemArray);
            }

            SqlClass sqlClass = new SqlClass();
            List<string> existProject = new List<string>();
            foreach (DataRow row in dt.Rows)
            {
                string proName = row["项目名称"].ToString();
                if (sqlClass.ExistProjectName(proName, "tbbusinessmanage"))
                {
                    existProject.Add(proName);
                }
            }
            if (existProject.Count > 0)
            {
                StringBuilder strWarming = new StringBuilder();
                strWarming.Append("您选择的Excel表格中的以下项目在数据库中已存在,不能再次添加：\r\n");
                foreach (string sproName in existProject)
                {
                    strWarming.Append(sproName);
                    strWarming.Append("\r\n");
                }
                XtraMessageBox.Show(strWarming.ToString());
                BeginInvoke(new MethodInvoker(() =>
                    {
                        btn_excelPath.Text = "";
                    gridControl2.DataSource = null;
                    btn_excelPath.Enabled = true;
                    btn_add.Enabled = true;
                }));
                return;
            }



            int insertRowsCount = 500;//一次性插入数据库行数
            int succeedrows = 0;//成功插入数据行数
            StringBuilder strSql = new StringBuilder();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow row = dt.Rows[i];
                string strProName = row["项目名称"].ToString();
                string strBusiness = row["商业运营"].ToString();
                string strCooperateType = row["合作方式"].ToString();
                string strKouDian = row["扣点"].ToString();
                string strCheckOutType = row["收银方式"].ToString();
                string strSaleType = row["销售形式"].ToString();
                string strPrice = row["售价"].ToString();
                string strSellRate = row["销售率"].ToString();
                if (strSellRate.Trim() == "" ||
                    strSellRate.Trim() == "-"  ||
                    strSellRate.Trim() == "不售")
                {
                    strSellRate = "0";
                }
                else
                {
                    if (strSellRate.Contains("%"))
                    {
                        strSellRate = strSellRate.Replace("%", "");
                        strSellRate = (float.Parse(strSellRate) / 100).ToString();
                    }
                   
                }
                string strMailHire = row["主力租金段"].ToString();
                string strHireYears = row["租赁年限"].ToString();
                string strAddRate = row["递增率"].ToString();
                string strHireRate = row["出租率"].ToString();
                if (strHireRate.Trim() == "" ||
                 strHireRate.Trim() == "-")
                {
                    strHireRate = "0";
                }
                else
                {
                    if (strHireRate.Contains("%"))
                    {
                        strHireRate = strHireRate.Replace("%", "");
                        strHireRate = (float.Parse(strHireRate)/100).ToString();
                    }                   
                }
                string strPropertyPrice = row["物业管理费"].ToString();
                string strConditionerPrice = row["空调使用费"].ToString();
                string strManageState = row["经营状况"].ToString();
               
                if (i % insertRowsCount == 0)
                {
                    strSql = new StringBuilder();
                    strSql.Append("Insert into tbbusinessmanage (");
                    strSql.Append("ProjectName,");
                    strSql.Append("Business,");
                    strSql.Append("CooperateType,");
                    strSql.Append("KouDian,");
                    strSql.Append("CheckOutType,");
                    strSql.Append("SaleType,");
                    strSql.Append("Price,");
                    strSql.Append("SellRate,");
                    strSql.Append("MailHire,");
                    strSql.Append("HireYears,");
                    strSql.Append("AddRate,");
                    strSql.Append("HireRate,");
                    strSql.Append("PropertyPrice,");
                    strSql.Append("ConditionerPrice,");
                    strSql.Append("ManageState)"); 
                    strSql.Append(" value  ");
                }
                strSql.Append("(");
                strSql.Append("'");
                strSql.Append(strProName);
                strSql.Append("','");
                strSql.Append(strBusiness);
                strSql.Append("','");
                strSql.Append(strCooperateType);
                strSql.Append("','");
                strSql.Append(strKouDian);
                strSql.Append("','");
                strSql.Append(strCheckOutType);
                strSql.Append("','");
                strSql.Append(strSaleType);
                strSql.Append("','");
                strSql.Append(strPrice);
                strSql.Append("',");
                strSql.Append(strSellRate);
                strSql.Append(",'");
                strSql.Append(strMailHire);
                strSql.Append("','");
                strSql.Append(strHireYears);
                strSql.Append("','");
                strSql.Append(strAddRate);
                strSql.Append("',");
                strSql.Append(strHireRate);
                strSql.Append(",'");
                strSql.Append(strPropertyPrice);
                strSql.Append("','");
                strSql.Append(strConditionerPrice);
                strSql.Append("','");
                strSql.Append(strManageState); 
                strSql.Append("'),");

                if ((i + 1) % insertRowsCount == 0
                    || i == dt.Rows.Count - 1)
                {
                    strSql.Remove(strSql.Length - 1, 1);
                    try
                    {
                        succeedrows += DbHelper.ExecuteSql(strSql.ToString());
                    }
                    catch (Exception ex)
                    {
                        XtraMessageBox.Show(ex.Message);
                    }

                }
            }

            if (dt.Rows.Count == succeedrows)
            {
                XtraMessageBox.Show("添加成功！");
                BeginInvoke(new MethodInvoker(() =>
                {
                    btn_excelPath.Text = "";
                    gridControl2.DataSource = null;
                    gridView2.GroupPanelText = "请选择想要导入的Excel表！";
                }));
            }
            else
            {
                int failedCount = dt.Rows.Count - succeedrows;
                XtraMessageBox.Show("共记" + dt.Rows.Count + "条数据，其中"
                    + failedCount + "条数据添加失败！");
            }
            BeginInvoke(new MethodInvoker(() =>
            {
               
                btn_excelPath.Enabled = true;
                btn_add.Enabled = true;
            }));
        }

        private void btn_add_Click(object sender, EventArgs e)
        {
            if (btn_excelPath.Text.Trim()=="")
            {
                XtraMessageBox.Show("请先选择Excel！");
                return;
            }
            if (!CheckDataValid())
            {
                return;
            }
             
            btn_excelPath.Enabled = false;
            btn_add.Enabled = false;
            Thread t = new Thread(AddData) { IsBackground = true };
            t.Start();
        }

        #region 数据完整性检测
        private bool CheckDataValid()
        {
            DataTable dt = (DataTable)gridControl2.DataSource;
            StringBuilder strErrors = new StringBuilder();
           
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                string strProName = dr["项目名称"].ToString();
                string strSellRate = dr["销售率"].ToString().Replace("%","");
                string strHireRate = dr["出租率"].ToString().Replace("%", ""); ;
                if (strProName.Trim() == "")
                {
                    strErrors.Append("第"+(i+2)+"行数据中的【项目名称】为空！\r\n"); 
                }
                float flTemp;
                if (strSellRate.Trim()!= "" && 
                    strSellRate.Trim()!="-" &&
                     strSellRate.Trim() != "不售" &&
                    !float.TryParse(strSellRate,out flTemp))
                {
                    strErrors.Append("第" + (i + 2) + "行数据中【销售率】数据有误，不是正确的百分比格式！\r\n");
                }
                if (strHireRate.Trim() != "" &&
                   strHireRate.Trim() != "-" &&
                   !float.TryParse(strHireRate, out flTemp))
                {
                    strErrors.Append("第" + (i + 2) + "行数据中【出租率】数据有误，不是正确的百分比格式！\r\n");
                } 
            }
            if (strErrors.ToString() != "")
            {                
                XtraMessageBox.Show("您选择的Excel中的数据存在以下错误：\r\n"+
                    strErrors);
                return false;
            }              
            return true;
        }
         
        private bool CheckExcelColumnsName(DataTable dt)
        {
            StringBuilder strErrors = new StringBuilder();
            if (!dt.Columns.Contains("项目名称"))
            {
                strErrors.Append("【项目名称】、");
            }
            if (!dt.Columns.Contains("商业运营"))
            {
                strErrors.Append("【商业运营】、");
            }
            if (!dt.Columns.Contains("合作方式"))
            {
                strErrors.Append("【合作方式】、");
            }
            if (!dt.Columns.Contains("扣点"))
            {
                strErrors.Append("【扣点】、");
            }
            if (!dt.Columns.Contains("收银方式"))
            {
                strErrors.Append("【收银方式】、");
            }
            if (!dt.Columns.Contains("销售形式"))
            {
                strErrors.Append("【销售形式】、");
            }
            if (!dt.Columns.Contains("售价"))
            {
                strErrors.Append("【售价】、");
            }
            if (!dt.Columns.Contains("销售率"))
            {
                strErrors.Append("【销售率】、");
            }
            if (!dt.Columns.Contains("主力租金段"))
            {
                strErrors.Append("【主力租金段】、");
            }
            if (!dt.Columns.Contains("租赁年限"))
            {
                strErrors.Append("【租赁年限】、");
            }
            if (!dt.Columns.Contains("递增率"))
            {
                strErrors.Append("【递增率】");
            }
            if (!dt.Columns.Contains("出租率"))
            {
                strErrors.Append("【出租率】");
            }
            if (!dt.Columns.Contains("物业管理费"))
            {
                strErrors.Append("【物业管理费】");
            }
            if (!dt.Columns.Contains("空调使用费"))
            {
                strErrors.Append("【空调使用费】");
            }
            if (!dt.Columns.Contains("经营状况"))
            {
                strErrors.Append("【经营状况】");
            }
            if (strErrors.ToString() != "")
            {
                XtraMessageBox.Show("您选择的Excel表数据不正常,缺少以下数据列:\r\n" +
                                    strErrors);
                return false;
            }
            return true;
        }
        #endregion
    }
}